package com.sinosoft.sm.system.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.sm.system.common.SystemContants;
import com.sinosoft.sm.system.common.exception.ObjectIsNotExistedException;
import com.sinosoft.sm.system.security.SecurityUtil;
import com.sinosoft.sm.user.entity.UserEntity;
import com.sinosoft.sm.user.service.api.UserService;

@Controller
@RequestMapping("/")
public class LoginController {
	
	@Autowired
	UserService userService;
	
	
	/**
	 * 默认页面
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model model) {
		model.addAttribute("Username", SecurityUtil.getUsername());
		return "app/index";
	}
	
	/**
	 * 获取用户帐号服务
	 * @return
	 */
	@RequestMapping(value="getUsernameService", method = RequestMethod.GET)
	@ResponseBody
	public String getLoginName(){
		return SecurityUtil.getUsername();
	}
	
	/**
	 * 登录页面
	 * @return
	 */
	@RequestMapping(value="login", method = RequestMethod.GET)
	public String login() {
		if(SecurityUtil.isLogin()) {
			return "redirect:/";
		}
		return "app/login";
	}
	
	/*@RequestMapping(value="login", method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "app/login";
	}*/

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName,
			Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM,userName);
		try {
			UserEntity userinfoData = userService.getUserByUsername(userName);
			if(SystemContants.USER_STATE_OFF.equals(userinfoData.getState())){
				model.addAttribute("errorMsg", "此账号已禁用");
			}else{
				model.addAttribute("errorMsg", "用户名或密码错误");
			}
		} catch (ObjectIsNotExistedException e) {
			model.addAttribute("errorMsg", "用户名不存在");
		}
		return "app/login";
	}

	@RequestMapping(value="logout", method = RequestMethod.POST)
	@ResponseBody
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "success";
	}
}
